package handlers

import (
	"strconv"
	"sysu-giep/internal/api/middleware"
	"sysu-giep/internal/database"
	"sysu-giep/internal/database/models"
	"sysu-giep/pkg/logger"
	"sysu-giep/pkg/response"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// GetMatches 获取匹配列表
// @Summary 获取匹配列表
// @Description 获取匹配列表，支持分页和筛选
// @Tags 匹配
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param page query int false "页码" default(1)
// @Param size query int false "每页大小" default(10)
// @Success 200 {object} response.PageResponse{data=[]map[string]interface{}}
// @Router /matches [get]
func GetMatches(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))

	var matches []models.ProjectMatch
	var total int64

	// 从数据库获取匹配列表
	query := database.DB.Model(&models.ProjectMatch{})

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		logger.ErrorLog("获取匹配总数失败", logger.Error(err))
		response.InternalServerError(c, "获取匹配列表失败")
		return
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Project").
		Preload("User").
		Offset(offset).
		Limit(size).
		Order("created_at DESC").
		Find(&matches).Error; err != nil {
		logger.ErrorLog("获取匹配列表失败", logger.Error(err))
		response.InternalServerError(c, "获取匹配列表失败")
		return
	}

	response.PageSuccess(c, matches, total, page, size)
}

// ConfirmMatch 确认匹配
// @Summary 确认匹配
// @Description 确认匹配结果
// @Tags 匹配
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "匹配ID"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /matches/{id}/confirm [post]
func ConfirmMatch(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	idStr := c.Param("id")

	matchID, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.BadRequest(c, "无效的匹配ID")
		return
	}

	// 查找匹配记录
	var match models.ProjectMatch
	if err := database.DB.Preload("Project").Preload("User").First(&match, matchID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			response.NotFound(c, "匹配记录不存在")
			return
		}
		logger.ErrorLog("查找匹配记录失败", logger.Error(err))
		response.InternalServerError(c, "确认匹配失败")
		return
	}

	// 检查权限：只有匹配的用户才能确认
	if match.UserID != userID {
		response.Forbidden(c, "无权限确认此匹配")
		return
	}

	// 更新匹配状态为已确认
	if err := database.DB.Model(&match).Update("is_confirmed", true).Error; err != nil {
		logger.ErrorLog("更新匹配状态失败", logger.Error(err))
		response.InternalServerError(c, "确认匹配失败")
		return
	}

	response.SuccessWithMessage(c, "匹配确认成功", nil)
}

// GetMyMatches 获取我的匹配
// @Summary 获取我的匹配
// @Description 获取当前用户的匹配列表
// @Tags 匹配
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param page query int false "页码" default(1)
// @Param size query int false "每页大小" default(10)
// @Success 200 {object} response.PageResponse{data=[]map[string]interface{}}
// @Router /matches/my [get]
func GetMyMatches(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))

	var matches []models.ProjectMatch
	var total int64

	// 获取我的匹配列表
	query := database.DB.Model(&models.ProjectMatch{}).Where("user_id = ?", userID)

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		logger.ErrorLog("获取我的匹配总数失败", logger.Error(err))
		response.InternalServerError(c, "获取匹配列表失败")
		return
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Project").
		Offset(offset).
		Limit(size).
		Order("created_at DESC").
		Find(&matches).Error; err != nil {
		logger.ErrorLog("获取我的匹配列表失败", logger.Error(err))
		response.InternalServerError(c, "获取匹配列表失败")
		return
	}

	response.PageSuccess(c, matches, total, page, size)
}
